<?php 

class Translator {
	private $phrases = array();
	
	function __construct(){
		global $_DB;
		$res = $_DB->query("SELECT * FROM ".$_DB->getPrefix()."phrases WHERE id_slug = 'site_name'");
		foreach($res as $phrase){
			$this->phrases[$phrase["id_slug"].'_'.$phrase["id_language"]] = $phrase["phrase"];
		}
	}
	
	function get($id_slug, $id_language = 1){
		global $_DB;
		if (empty($this->phrases[$id_slug.'_'.$id_language])) {
			$res = $_DB->query("SELECT * FROM ".$_DB->getPrefix()."phrases WHERE id_slug = '".$id_slug."'");
			if (count($res) > 0) {
				foreach($res as $phrase){
					$this->phrases[$phrase["id_slug"].'_'.$phrase["id_language"]] = $phrase["phrase"];
				}
			} else {
				$this->phrases[$id_slug.'_'.$id_language] = '['.$id_slug.']';
			}
		}

		return $this->phrases[$id_slug.'_'.$id_language];
	}
	
	function traslate($str, $id_lang){
		//$str = '{VOCABULARY|site_name} jcdio cdjio cdij cdo jiod {VOCABULARY|bulli_bulli}cdio cdjio cjdijcd';
		$pattern = '/\{VOCABULARY\|[a-z,_]*\}*/';
		preg_match_all($pattern, $str, $matches);
		
		//var_dump($matches);
		/*
		 * 
			array(1) {
  				[0]	=>	array(2) {
    							[0]	=> string(22) "{VOCABULARY|site_name}"
    							[1]	=> string(24) "{VOCABULARY|bulli_bulli}"
  						}
			}
		 * */
		foreach($matches[0] as $phrase){
			$id_slug = substr($phrase, 12, strlen($phrase)-13);
			$translated = $this->get($id_slug, $id_lang);
			$str = str_replace($phrase, $translated, $str);
		}
		return $str;
	}
}

?>